import { messages, queryCurrencyPrecision, deepFullCopy } from "share/common";
import React from 'react'
import {connect} from 'react-redux'
import { Row, Col, Tag, Button, Popover, Alert, Popconfirm, message, Tooltip} from 'antd'
import 'styles/my-account/invoice.scss'
import expenseService from 'containers/my-account/expense.service'
import Condition from 'components/condition';
import InvoiceDetail from 'containers/my-account/components/invoice-detail';
import wechatIcon from 'images/expense/icon-wechat.png'
import alipayIcon from 'images/expense/icon-alipay.png'
import { formatNumber } from "share/common";

const { If } = Condition;

class Invoice extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      invoices: deepFullCopy(props.invoiceList || []),
    };
  }
  /*获取币种精度*/
  getCurrencyPrecision = (invoice) => {
    if (invoice && invoice.vatInvoiceCurrencyCode) {
      return queryCurrencyPrecision(invoice.vatInvoiceCurrencyCode);
    }
    return queryCurrencyPrecision();
  };

  componentDidMount() {
    this.changeProps(this.props.invoiceList);
  }

  componentWillReceiveProps(nextProps) {
    nextProps.invoiceList !== null && this.changeProps(nextProps.invoiceList);
    let { invoices } = this.state;
    let propsInvoices = deepFullCopy(nextProps.invoiceList);
    propsInvoices.map(item => {
      invoices.map(invoiceItem => {
        //防止invoices更新时，showMore由true变为false
        invoiceItem.id === item.id && (item.showMore = invoiceItem.showMore);
      })
    });
    this.setState({ invoices: propsInvoices })
  }

  changeProps = (invoiceList) => {
    invoiceList && invoiceList.length > 0 && invoiceList.map(item => {
      item.invoiceGoods && item.invoiceGoods.map((goods, index) => {
        goods.index = index;
      });
    })
  };

  /*获取是否免贴补标签*/
  getIsInvoiceFree = (invoice) => {
    let isInvoiceFree = false;
    invoice.invoiceLabels && invoice.invoiceLabels.map(label => {
      if (label.type === 'INVOICE_FREE') {
        isInvoiceFree = true;
      }
    });
    return isInvoiceFree;
  };

  /*获取是否免打印*/
  getInvoiceFreePrint = (invoice) => {
    let invoiceFreePrint = false;
    let isFinancial = window.location.pathname.indexOf('financial-management') > -1;
    invoice.receiptLabels && invoice.receiptLabels.map(label => {
      if (label.type === 'INVOICE_FREE') {
        !isFinancial && (invoiceFreePrint = true);
      }
    });
    return invoiceFreePrint;
  };
  // 显示标签信息
  showMessage = (item) => {
    if (!item.name) {
      return item.toast;
    }
    if (!item.toast) {
      return item.name;
    }
    return `${item.name} : ${item.toast}`;
  };

  handlePrint = (e, invoice) => {
    e.stopPropagation();
    expenseService.printInvoice(invoice.id).then((res) => {
      window.open(res.data.rows.fileURL, "_blank");
    }).catch((e) => {
      message.error(messages('common.operate.filed'));//操作失败
    });
  };

  //展开／收起详情
  handleShowBrief = (index, isMore) => {
    let { invoices } = this.state;
    invoices[index].showMore = isMore;
    this.setState({ invoices })
  };

  render() {
    const { disabledEdit, handleEdit, canExpense, handleDelete, isPreViewCallBack, handlePreViewCallBack, isOCRList, createType } = this.props;
    const { invoices } = this.state;
    return((invoices && invoices.length > 0) ? (
      <div>
        {invoices.map((invoice, index) => {
          let tags = [];
          this.getIsInvoiceFree(invoice) && tags.push({text: messages('common.invoice.free'), color: 'blue'});
          let goodsName;
          let goodsNameArray = [];
          if (invoice && invoice.invoiceGoods && invoice.invoiceGoods.length > 0) {
            invoice.invoiceGoods.map(item => {
              let str;
              if (item.goodsName) {
                let goodsNameArray = item.goodsName.match(/\*(\S*)\*/);
                if (goodsNameArray && goodsNameArray.length > 1) {
                  str = goodsNameArray[1];
                } else {
                  str = item.goodsName;
                }
              }
              if (str) {
                goodsNameArray.push(str)
              } else {
                goodsNameArray.push(item.goodsName)
              }
            })
            let goodsNameNoRepeat = new Set(goodsNameArray);
            goodsNameArray = [...goodsNameNoRepeat];
          }
          goodsName = goodsNameArray.join(',');
          invoice.invoiceGoods && invoice.invoiceGoods.length > 0 && invoice.invoiceGoods.map(item => {
            item.vatInvoiceCurrencyCode = invoice.vatInvoiceCurrencyCode;
          });
          console.log('invoiceinvoiceinvoiceinvoiceinvoice', invoice)
          console.log("isOCRListisOCRListisOCRListisOCRList", isOCRList)
          console.log("disabledEditdisabledEditdisabledEdit", disabledEdit)
          return (!invoice.showMore && canExpense) ? (
            <div className="invoice-brief-mode" key={`receipt${index}`}>
              <Row>
                <Col span={6} className="invoice-brief-amount-area" >
                  {<div>
                    <a onClick={() => this.handleShowBrief(index, true)}>{messages('my-account.key47'/*查看详情*/)}</a>
                    {invoice.originAttachment ? ['PDF', 'IMAGE'].includes(invoice.originAttachment.fileType) ? <a style={{ marginLeft: '10px', textDecoration: 'none' }} href={invoice.originAttachment.fileURL} target="_blank">查看原件</a> : <a style={{ marginLeft: '10px', textDecoration: 'none' }} href={invoice.originAttachment.fileURL} download={invoice.originAttachment.fileName}>查看原件</a> : ''}
                  </div>}
                  <Row className="invoice-brief-amount-detail" >
                    <Col span={14}>
                      <Popover content={`${messages('my-account.key48')/*金额合计*/}（${messages('my-account.key180')/*不含税*/}）`}>
                        {messages('my-account.key48'/*金额合计*/)}（{messages('my-account.key180')/*不含税*/}）
                      </Popover>
                    </Col>
                    <Col span={10}>
                      {typeof invoice.feeWithoutTax === 'number' ?
                        formatNumber(invoice.feeWithoutTax / 100) : '-'}
                    </Col>
                    <Col span={14}>{messages('common.currency')/*币种*/}</Col>
                    <Col span={10}>{invoice.vatInvoiceCurrencyCode || '-'}</Col>
                    <Col span={14}>{messages('my-account.key49'/*税额合计*/)}</Col>
                    <Col span={10}>
                      {typeof invoice.tax === 'number' ?
                        formatNumber(invoice.tax / 100) : '-'}
                    </Col>
                    <Col span={14}>{messages('my-account.key50'/*价税合计*/)}</Col>
                    <Col span={10}>{formatNumber(invoice.fee / 100)}</Col>
                  </Row>
                </Col>
                <Col span={18} className="invoice-brief-content-area">
                  <div className="invoice-type">
                    <Popover placement="topLeft" content={invoice.type}>{invoice.type}</Popover>
                    <div className="operate-buttons">
                      {/* <If value={(invoice.checkResult !== 'R_0000' || (isOCRList && invoice.editable)) && !disabledEdit}> */}
                      <If value={createType === 1 ? invoice.cardsignType === 'HAND' : true}>
                        <Button icon="edit" type="primary" size="small" className="button-update"
                                onClick={() => handleEdit(invoice,index)}>{messages('common.update')/*修改*/}</Button>
                      </If>
                      {/* </If> */}
                      <If value={!this.getInvoiceFreePrint(invoice) && invoice.pdfUrl && !invoice.pdfDamaged && invoice.id}>
                        <Button icon="printer" type="primary" size="small" className="button-print"
                                onClick={e => this.handlePrint(e, invoice)}>{messages('common.print')/*打印*/}</Button>
                      </If>
                      <If value={!disabledEdit}>
                        <Popconfirm
                          onConfirm={() => handleDelete(invoice, index)}
                          title={messages('common.confirm.delete')/*确定要删除吗*/}
                        >
                          <Button
                            icon="delete"
                            size="small"
                            type="primary"
                            className="button-delete"
                            loading={invoice.deleteLoading}
                            onClick={e => e.stopPropagation()}
                          >{messages('common.delete')/*删除*/}</Button>
                        </Popconfirm>
                      </If>
                    </div>
                  </div>
                  <Row className="invoice-brief-content" gutter={10}>
                    {(invoice.billingTime) && (
                      <Col span={12}>
                        <span className="title">{messages('my-account.key3'/*开票日期*/)}：</span>&nbsp;
                        {invoice.billingTime ? new Date(invoice.billingTime * 1000).format('yyyy-MM-dd') : ''}
                      </Col>
                    )}
                    <Col span={12}>
                      <span className="title">{messages('my-account.key4'/*发票代码*/)}：</span>&nbsp;
                      {invoice.billingCode}
                    </Col>
                    <Col span={12}>
                      <span className="title">{messages('my-account.key6'/*发票号码*/)}：</span>&nbsp;
                      {invoice.billingNo}
                    </Col>
                    <Col span={12}>
                      <span className="title">{messages('my-account.key51'/*销售方*/)}：</span>&nbsp;
                      <Popover content={invoice.payee} overlayStyle={{width: 200}}>
                        {invoice.payee}
                      </Popover>
                    </Col>
                    <Col span={12}>
                      <span className="title">{messages('my-account.key52'/*购买方*/)}：</span>&nbsp;
                      <Popover content={invoice.title} overlayStyle={{width: 200}}>
                        {invoice.title}
                      </Popover>
                    </Col>
                    <Col span={24}>
                      <span className="title">{messages('my-account.key157')/*服务名称*/}：</span>&nbsp;
                      <Popover content={goodsName || '-'} overlayStyle={{width: 200}}>
                        {goodsName || '-'}
                      </Popover>
                    </Col>
                  </Row>
                </Col>
              </Row>
              <div style={{padding: '0 10px'}}>
                {invoice.pdfDamaged && <span style={{float: 'left', marginRight: '5px'}}><Alert className={'alert-tip'}
                                                                                                style={{
                                                                                                  fontSize: "12px",
                                                                                                  padding: "2px 5px 2px 30px",
                                                                                                }}
                                                                                                message={messages('my-account.key164')/*电子票来源中的原件已损坏*/}
                                                                                                type="error"
                                                                                                showIcon/>&nbsp;</span>}
                {invoice.receiptLabels.length > 0 && invoice.receiptLabels.map((item, index) => {
                  return <Tag key={`receiptTag${index}`} color={item.level === 'ERROR' ? 'red' : 'blue'}>{item.name}</Tag>
                })}
                {invoice.type.substr(0, 2) == "全电"&&<Tag color={'blue'}>{`全电发票`}</Tag>}
                {invoice.PYTerrorList && invoice.PYTerrorList.length > 0 && invoice.PYTerrorList.map((item, index) => {
                  return ( <Tooltip zIndex='999' placement="top" title={<span>{item.message}</span>}>
                  <Tag key={`PYTerrorList${index}`} color={'red'}>{item.title}</Tag>
                </Tooltip>)
                 
                })}
                
              </div>
              <If value={~['APPCARDSIGN', 'JSCARDSIGN', 'WXFWCARDSIGN'].indexOf(invoice.cardsignType)}>
                <img src={wechatIcon} className="card-sign-type-icon"/>
              </If>
              <If value={~['ALICARDSIGN'].indexOf(invoice.cardsignType)}>
                <img src={alipayIcon} className="card-sign-type-icon"/>
              </If>
            </div>
          ) : (
            <div className="invoice" key={`receipt${index}`}>
              {
                invoice.receiptLabels && invoice.receiptLabels.length > 0 && (
                  <div className='tip-wrap'>
                    {/* 非普通标签单独一行显示*/}
                    {invoice.receiptLabels.filter(item => item.level !== 'INFO').map(item =>
                      <Alert message={this.showMessage(item)}
                             key={item.name}
                             type={item.level === 'ERROR' ? 'error' : 'info'}
                             showIcon/>
                    )}
                    {/* 普通标签拼接成一行显示*/}
                    {invoice.receiptLabels.filter(item => item.level === 'INFO').length > 0 && (
                      <Alert message={invoice.receiptLabels.filter(item => item.level === 'INFO').map(item => item.name).join('/')}
                             type="info"
                             showIcon/>
                    )}
                  </div>
                )
              }
               {
                invoice.PYTerrorList && invoice.PYTerrorList.length > 0 && (
                  <div className='tip-wrap'>
                    {invoice.PYTerrorList.map(item =>
                      <Alert message={`${item.title}:${item.message}`}
                             key={item.title}
                             type={'error'}
                             showIcon/>
                    )}
                  </div>
                )
              }
              <div className="invoice-type">{invoice.type}</div>
              <InvoiceDetail
                invoice={invoice}
                canExpense={canExpense}
                getCurrencyPrecision={this.getCurrencyPrecision}
                handlePrint={this.handlePrint}
                getInvoiceFreePrint={this.getInvoiceFreePrint}
                handleShowBrief={(value) => this.handleShowBrief(index, value)}
                isPreViewCallBack={isPreViewCallBack}
                handlePreViewCallBack={handlePreViewCallBack}
              />
            </div>
          )
        })}
      </div>
    ) : <div/>)
  }
}

Invoice.propTypes = {
  invoiceList: React.PropTypes.array.isRequired, // 费用数据
  disabledEdit: React.PropTypes.bool, // 是否可编辑
  handleEdit: React.PropTypes.func, // 编辑回调
  handleDelete: React.PropTypes.func, // 删除回调
  canExpense: React.PropTypes.bool, //发票能否生成费用
  isOCRList: React.PropTypes.bool, //是否为ocr列表
};

Invoice.defaultProps={
  canExpense: true,
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    profile: state.login.profile
  }
}

export default connect(mapStateToProps)(Invoice);
